<script setup lang="ts">
import type { VbenFormSchema } from '@vben/common-ui';

import { useVbenModal } from '@vben/common-ui';
import { SUPPORT_LANGUAGES } from '@vben/constants';
import { $t } from '@vben/locales';
import { isJSON } from '@vben/utils';

import { useVbenForm } from '#/adapter/form';

const props = defineProps<{
  lang: string;
}>();

const emit = defineEmits<{ save: [{}] }>();

const [BasicModal, modalApi] = useVbenModal({
  fullscreenButton: false,
  onConfirm: handleConfirm,
  onOpenChange: async (isOpen) => {
    if (!isOpen) {
      return null;
    }
    modalApi.lock(true);
    const newSchema: VbenFormSchema[] = [];
    SUPPORT_LANGUAGES.forEach((item) => {
      newSchema.push({
        component: 'Input',
        componentProps: {
          placeholder: $t('ui.placeholder.input'),
        },
        rules: 'required',
        fieldName: item.value,
        label: item.label,
      });
    });

    formApi.setState({ schema: newSchema });
    const { lang } = props;
    if (isJSON(lang)) {
      const map = JSON.parse(lang);
      await formApi.setValues(map);
    }
    modalApi.unlock();
  },
});

const [BasicForm, formApi] = useVbenForm({
  commonConfig: {
    labelWidth: 100,
  },
  showDefaultActions: false,
});

async function handleConfirm() {
  try {
    modalApi.lock(true);
    const { valid } = await formApi.validate();
    if (valid) {
      const data = await formApi.getValues();
      emit('save', data);
      modalApi.close();
    }
  } catch (error) {
    console.error(error);
  } finally {
    modalApi.unlock();
  }
}
</script>

<template>
  <BasicModal
    :close-on-click-modal="false"
    :title="$t('common.locales')"
    class="w-[550px]"
  >
    <BasicForm />
  </BasicModal>
</template>
